<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ page import="java.net.*" %>
<%
    // 编码，解决中文乱码
    String str = URLEncoder.encode(request.getParameter("name"),"utf-8");
    // 设置 name 和 url cookie
    Cookie name = new Cookie("name",
            str);
    Cookie url = new Cookie("url",
            request.getParameter("url"));

    // 设置cookie过期时间为24小时。
    name.setMaxAge(60*60*24);
    url.setMaxAge(60*60*24);

    // 在响应头部添加cookie
    response.addCookie( name );
    response.addCookie( url );
%>
<html>
<head>
    <title>设置 Cookie</title>
</head>
<body>

<h1>设置 Cookie</h1>

<ul>
    <li><p><b>网站名:</b>
        <%= request.getParameter("name")%>
    </p></li>
    <li><p><b>网址:</b>
        <%= request.getParameter("url")%>
    </p></li>
</ul>

<%
    Cookie cookie = null;
    Cookie[] cookies = null;
    // 获取 cookies 的数据,是一个数组
    cookies = request.getCookies();
    if( cookies != null ){
        out.println("<h2> 查找 Cookie 名与值</h2>");
        for (int i = 0; i < cookies.length; i++){
            cookie = cookies[i];

            out.print("参数名 : " + cookie.getName());
            out.print("<br>");
            out.print("参数值: " + URLDecoder.decode(cookie.getValue(), "utf-8") +" <br>");
            out.print("------------------------------------<br>");
        }
    }else{
        out.println("<h2>没有发现 Cookie</h2>");
    }
%>


<%
    Cookie cookie2 = null;
    Cookie[] cookies2 = null;
    // 获取当前域名下的cookies，是一个数组
    cookies2 = request.getCookies();
    if( cookies2 != null ){
        out.println("<h2> 查找 Cookie 名与值</h2>");
        for (int i = 0; i < cookies2.length; i++){
            cookie2 = cookies2[i];
            if((cookie2.getName( )).compareTo("name") == 0 ){
                cookie2.setMaxAge(0);
                response.addCookie(cookie2);
                out.print("删除 Cookie: " +
                        cookie2.getName( ) + "<br/>");
            }
            out.print("参数名 : " + cookie2.getName());
            out.print("<br>");
            out.print("参数值: " + URLDecoder.decode(cookie2.getValue(), "utf-8") +" <br>");
            out.print("------------------------------------<br>");
        }
    }else{
        out.println("<h2>没有发现 Cookie</h2>");
    }
%>

</body>
</html>